<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Controller\Api;

use App\Controller\AbstractController;
use App\Middleware\AuthMiddleware;

use App\Model\Article;
use App\Model\ArticleLike;
use App\Model\ArticleTag;
use App\Model\Comment;
use App\Model\User;
use App\Model\UserRole;
use Hyperf\Context\Context;
use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\DeleteMapping;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\PostMapping;
use Hyperf\HttpServer\Annotation\PutMapping;
use Hyperf\HttpServer\Annotation\RequestMapping;

#[Middlewares([AuthMiddleware::class])]
#[Controller]
class ProtalController extends AbstractController
{
    #[PutMapping(path: '/protal/user/updateProfile')]
    public function updateProfile()
    {
        $user_id = Context::get('uid');
        $params = $this->request->all();
        User::query()->where('id', $user_id)->update([
            'bio' => $params['bio'],
            'email' => $params['email'],
            'sex' => $params['sex'],
            'os' => $params['os'],
        ]);
        return success();
    }

    #[GetMapping(path: '/protal/user/myArticle')]
    public function myArticle()
    {
        $user_id = Context::get('uid');
        $title = $this->request->input('title', '');
        $pageNum = $this->request->input('pageNum', 1);
        $pageSize = $this->request->input('pageSize', 10);
        $query = Article::query()
            ->select('id', 'user_id', 'user_id as userId', 'category_id', 'category_id as categoryId', 'title', 'summary', 'content', 'content_md as contentMd', 'cover', 'create_time as createTime', 'read_type', 'is_stick as isStick', 'status', 'quantity', 'create_time as createTime')
            ->where('user_id',$user_id)
            ->when(!empty($title), function ($query) use ($title) {
                $query->where('title', 'like', '%' . $title . '%');
            });
        $total = $query->count();
        $list = $query->with(['tags', 'category', 'user'])->orderBy('is_stick', 'desc')
            ->forPage($pageNum, $pageSize)->get();
        // 添加分类名称到原数组同级
        foreach ($list as &$article) {
            $article->categoryName = $article->category->name;
            $article->categoryId = $article->category->id;
            $article->cover = replaceImage($article->cover);
            $article->commentNum = null;
            $article->likeNum = null;
            unset($article->category); // 可选：移除整个 category 对象
            $article->avatar = $article->user->avatar;
            $article->nickname = $article->user->nickname;
            unset($article->user); // 可选：移除整个 user 对象
        }
        $data['searchCount'] = true;
        $data['current'] = (int) $pageNum;
        $data['size'] = (int) $pageSize;
        $data['total'] = $total;
        $data['records'] = $list;
        $data['pages'] = ceil($data['total'] / $pageSize);
        return success($data);
    }


    #[GetMapping(path: '/protal/user/myReply')]
    public function myReply()
    {
        $pageNum = $this->request->input('pageNum', 1);
        $pageSize = $this->request->input('pageSize', 10);
        $query = Comment::query()->where('user_id', Context::get('uid'));
        $total = $query->count();
        $list = $query->with(['article', 'user'])->orderBy('create_time', 'desc')
            ->forPage($pageNum, $pageSize)->get();
        foreach ($list as &$reply) {
            $reply->replyNickname = $reply->user->nickname;
            $reply->articleId = $reply->article_id;
            if ($reply->article){
                $reply->articleTitle = $reply->article->title;
            }
            $reply->createTime = $reply->create_time;
            // $reply->cover = replaceImage($reply->cover);
            // $reply->commentNum = null;
            // $reply->likeNum = null;
            unset($reply->article); // 可选：移除整个 category 对象
            // $reply->avatar = $reply->user->avatar;
            // $reply->nickname = $reply->user->nickname;
            unset($reply->user); // 可选：移除整个 user 对象
        }

        $data['searchCount'] = true;
        $data['current'] = (int) $pageNum;
        $data['size'] = (int) $pageSize;
        $data['total'] = $total;
        $data['records'] = $list;
        $data['pages'] = ceil($data['total'] / $pageSize);
        return success($data);
    }

    #[DeleteMapping(path: '/protal/user/delMyComment/{id}')]
    public function delMyComment($id)
    {
        Comment::query()->where('id', $id)->delete();
        return success();

    }


    #[GetMapping(path: '/protal/user/comment')]
    public function comment()
    {
        $pageNum = $this->request->input('pageNum', 1);
        $pageSize = $this->request->input('pageSize', 10);
        $user_id = Context::get('uid');
        $article_id_arr = Article::where('user_id', $user_id)->pluck('id')->toArray();
        $query = Comment::query()->whereIn('article_id', $article_id_arr);
        $total = $query->count();
        $list = $query->with(['article', 'user'])->orderBy('create_time', 'desc')->forPage($pageNum, $pageSize)->get();
        foreach ($list as &$reply) {
            $reply->replyNickname = $reply->user->nickname;
            $reply->articleId = $reply->article_id;
            if ($reply->article){
                $reply->articleTitle = $reply->article->title;
            }
            $reply->createTime = $reply->create_time;
            // $reply->cover = replaceImage($reply->cover);
            // $reply->commentNum = null;
            // $reply->likeNum = null;
            unset($reply->article); // 可选：移除整个 category 对象
            // $reply->avatar = $reply->user->avatar;
            // $reply->nickname = $reply->user->nickname;
            unset($reply->user); // 可选：移除整个 user 对象

            $reply->likeCount = ArticleLike::query()->where('article_id', $reply->article_id)->count();
        }

        $data['searchCount'] = true;
        $data['current'] = (int) $pageNum;
        $data['size'] = (int) $pageSize;
        $data['total'] = $total;
        $data['records'] = $list;
        $data['pages'] = ceil($data['total'] / $pageSize);
        return success($data);
    }


    #[GetMapping(path: '/protal/user/myLike')]
    public function myLike()
    {
        $pageNum = $this->request->input('pageNum', 1);
        $pageSize = $this->request->input('pageSize', 10);
        $user_id = Context::get('uid');
        $article_id_arr = Article::where('user_id', $user_id)->pluck('id')->toArray();
        $query = ArticleLike::query()->whereIn('article_id', $article_id_arr);
        $total = $query->count();
        $list = $query->with(['article', 'user'])->forPage($pageNum, $pageSize)->get();
        foreach ($list as &$like) {
            $like->title = $like->article->title;
        }
        $data['searchCount'] = true;
        $data['current'] = (int) $pageNum;
        $data['size'] = (int) $pageSize;
        $data['total'] = $total;
        $data['records'] = $list;
        $data['pages'] = ceil($data['total'] / $pageSize);
        return success($data);
    }


    #[GetMapping(path: '/protal/user/statistics')]
    public function statistics()
    {
        $user_id = Context::get('uid');
        $article_id_arr = Article::where('user_id', $user_id)->pluck('id')->toArray();
        $followers1 = Comment::query()->whereIn('article_id', $article_id_arr)->groupBy('user_id')->count();
        $likes_user = ArticleLike::query()->whereIn('article_id', $article_id_arr)->groupBy('user_id')->count();
        $followers = $followers1 + $likes_user;
        $likes = ArticleLike::query()->whereIn('article_id', $article_id_arr)->count();
        return success([
            'followers' => $followers,
            'likes' => $likes,
            'posts' => count($article_id_arr),
        ]);
    }


}
